package com.arvato.wxwork.controller.front.member;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.arvato.minipro.bean.bean_dto.common.PageData;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.common.config_bean.WxworkConfig;
import com.arvato.common.config_bean.ZSTBrandNumberConfig;
import com.arvato.wxwork.bean.bean_do.member.WxworkExternalInfoDo;
import com.arvato.wxwork.bean.bean_do.member.WxworkMemberBindDo;
import com.arvato.wxwork.bean.bean_vo.member.WxworkExternalInfoVo;
import com.arvato.wxwork.service.member.WxworkExternalService;
import com.arvato.wxwork.service.member.WxworkMemberBindService;
import com.arvato.wxwork.service.member.WxworkMemberInfoService;


/**
 * 企业微信外部联系人接口
 * 外部联系人列表查询，与员工绑定绑定，存储
 * @author ZHAN655
 */
@RestController
@RequestMapping("/wxwork/external")
@EnableAsync
public class WxworkExternalController{
	
	@Autowired
	private WxworkMemberBindService wxworkMemberBindService;
	
	@Autowired
	private WxworkMemberInfoService wxworkMemberInfoService;
	
	@Autowired
	private WxworkExternalService wxworkExternalService;

	private Logger logger = LoggerFactory.getLogger(WxworkExternalController.class);
	
	/**
	 * 外部联系人批量查询接口 支持分页
	 * @param req
	 * @param param：支持参数(keyword，brand， staffId, phoneGroupId,pageNum, pageSize)
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/list")
	public Result list(HttpServletRequest req, @RequestParam Map<String, Object> param) {
		Query query = new Query(param);
		PageData pageData = wxworkExternalService.listExternalByQuery(query, query.getPageNum(), query.getPageSize());
		return Result.success(pageData);
	}
	
	/**
	 * 根据分组查询外部联系人
	 * @param req
	 * @param param
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value="/list/bygroup")
	public Result noGroupPeople(HttpServletRequest req, @RequestParam Map<String, Object> param) {
		Query query = new Query(param);
		Object object = query.get("phoneGroupId");
		PageData pageData;
		if(object != null && !(object + "").equals("")) {
			// 根据分组ID查
			query.remove("staffId");
			pageData = wxworkExternalService.listExternalByQuery(query, query.getPageNum(), query.getPageSize());
		}else {
			// 没有分组ID 查询没有分组的人
			pageData = wxworkExternalService.getNoGroupPeople(query, query.getPageNum(), query.getPageSize());
		}
		List<?> data = pageData.getData();
		for(Object obj: data) {
			WxworkExternalInfoVo externalInfoVo = (WxworkExternalInfoVo)obj;
			String memberId = externalInfoVo.getMemberId();
			if(memberId == null || memberId.equals("")) {
				continue;
			}
			String brand = externalInfoVo.getBrand();
			Map<String, Object> resultMap = wxworkMemberInfoService.getMemberInfo(memberId, externalInfoVo.getBrand());
			Map<String, Object> dataMap = (Map<String, Object>)resultMap.get("Result");
			Map<String, Object> memberInfo = (Map<String, Object>)dataMap.get("MemberInfo");
			if(memberInfo != null) {
				externalInfoVo.setMemberType(ZSTBrandNumberConfig.BRAND_MEMBER_MAP.get(brand + "_" + memberInfo.get("MemberType")));
			}
		}
		return Result.success(pageData);
	}
	
	/**
	 * 根据ID获取外部联系人详情
	 * @param req
	 * @param externalId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/get")
	public Result detail(HttpServletRequest req, String externalId) {
		// 获取本地外部联系人详情 并且同步本地外部联系人信息
		WxworkExternalInfoVo localExternalInfo = wxworkExternalService.getExternalById(externalId);
		WxworkExternalInfoDo remoteExternalInfo;
		try {
			remoteExternalInfo = wxworkExternalService.getRemoteExternalInfo(localExternalInfo.getWxExternalUserid());
		} catch (Exception e) {
			e.printStackTrace();
			return Result.success(localExternalInfo);
		}
		return Result.success(remoteExternalInfo);
	}
	
	/**
	 * 接收一组外部联系人的userid，检查其中那些绑定了，那些没有绑定
	 * 绑定了的提示前台当前人已经被其他人绑定
	 * 没有绑定的进行绑定并且将结果告知前台
	 * @param req
	 * @param externalUserIdsStr
	 * @param brand
	 * @param staffId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/bind")
	public Result check(HttpServletRequest req, String externalUserIdsStr, String brand, String staffId) {
		System.out.println(externalUserIdsStr);
		logger.info("判断外部联系人是否已经被绑定");
		List<WxworkExternalInfoDo> failList = new ArrayList<WxworkExternalInfoDo>();
		List<WxworkExternalInfoDo> hadBindList = new ArrayList<WxworkExternalInfoDo>();
		String[] externalUserIds = externalUserIdsStr.split(",");
		for(String externalUserId : externalUserIds) {
			// 请求腾讯接口 获取更多外部联系人信息
			long startTime = System.currentTimeMillis();
			WxworkExternalInfoDo externalDo;
			try {
				externalDo = wxworkExternalService.getRemoteExternalInfo(externalUserId);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
			externalDo.setWxExternalUserid(externalUserId);
			externalDo.setBrand(brand);
			externalDo.setCorpid(WxworkConfig.CORPID);
			try {
				// 然后更新或者插入这些外部联系人的信息
				int row = wxworkExternalService.ayncUpdate(externalDo);
				if(row == 1) {
					long endTime = System.currentTimeMillis();
					logger.info("调用腾讯外部联系人信息接口用时:" + (endTime - startTime));
					// 然后查询是否被绑定
					boolean flag = wxworkMemberBindService.checkBind(externalDo.getExternalId(), brand);
					if (flag) {
						hadBindList.add(externalDo);
					}else {
						// 如果没有绑定 就走绑定流程
						WxworkMemberBindDo wxworkMemberBindDo = new WxworkMemberBindDo();
						wxworkMemberBindDo.setStaffId(staffId);
						wxworkMemberBindDo.setExternalId(externalDo.getExternalId());
						wxworkMemberBindDo.setCreateTime(new Date());
						row = wxworkMemberBindService.insert(wxworkMemberBindDo);
						if(row == 0) {
							failList.add(externalDo);
						}
					}
				}else {
					failList.add(externalDo);
				}
			} catch (Exception e) {
				logger.error("外部联系人绑定时候报错：", e);
				e.printStackTrace();
				failList.add(externalDo);
			}
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("hadBindList", hadBindList);
		resultMap.put("failList", failList);
		return Result.success(resultMap);
	}
	
}
